package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.LRSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.EcDequiAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.EcDequiBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class EcDequipmentActivity extends MyBaseActivity {

    @BindView(R.id.recycler_view)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private EcDequiAdapter ecDequiAdapter;
    private String[] deviceTypeArray = {"全部", "气象", "水文"};
    private int deviceType = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ecology_dequipment;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("生态设备管理");
        showTopRightImg(R.mipmap.icon_filte_white2);
    }

    @Override
    protected void initData() {
        if (ScreenUtils.isTablet()) {
            GridLayoutManager manager1 = new GridLayoutManager(context, 2);
            recycler.setLayoutManager(manager1);
            recycler.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtils.dp2px(ItemDecorationSpaces), true));
        } else {
            LinearLayoutManager manager1 = new LinearLayoutManager(context);
            recycler.setLayoutManager(manager1);
            recycler.addItemDecoration(new TopSpaceItemDecoration());
            recycler.addItemDecoration(new BottomSpaceItemDecoration());
            recycler.addItemDecoration(new LRSpaceItemDecoration());
        }

        ecDequiAdapter = new EcDequiAdapter();
        if (isOpenLoadAnimation) {
            ecDequiAdapter.isFirstOnly(isFirstOnly);
            ecDequiAdapter.openLoadAnimation(animationType);
        }

        ecDequiAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(ecDequiAdapter);
        ecDequiAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                EcDequiBean.DataBean dataBean = ecDequiAdapter.getData().get(position);

                String lngStr = dataBean.getLon();
                String latStr = dataBean.getLat();

                switch (view.getId()) {
                    case R.id.layout_nav:
                        Bundle bundle = new Bundle();
                        bundle.putString("lng", lngStr);
                        bundle.putString("lat", latStr);
                        bundle.putBoolean("isFire", false);
                        IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), NaviMapActivity.class, bundle);
                        break;
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getDequiList(1);
    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        showProtectPop();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getDequiList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(ecDequiAdapter.getData(), Constant.PAGE_SIZE);
                    getDequiList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 设备列表
     */
    private void getDequiList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        if (deviceType == 0) {
            hashMap.put("deviceType", null);
        } else {
            hashMap.put("deviceType", deviceType);
        }
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_EC_DEVICE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            EcDequiBean ecDequiBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ecDequiBean = new EcDequiBean();
                                ecDequiBean = gson.fromJson(result, EcDequiBean.class);
                                List<EcDequiBean.DataBean> dataBeans = ecDequiBean.getData();
                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        for (int i = 0; i < dataBeans.size(); i++) {
                                            EcDequiBean.DataBean dataBean = dataBeans.get(i);
                                            String heartTime = dataBean.getHeartTime();
                                            String status = dataBean.getStatus();


                                            boolean isOnline = false;
                                            if (!StringUtils.isEmpty(status)) {
                                                if (status.equals("0")) { //0 离线  1在线
                                                    //如果当前时间与心跳时间的差值大于12小时，说明设备离线
                                                    isOnline = false;
                                                } else {
                                                    isOnline = true;

                                                }

                                            } else {
                                                if (!StringUtils.isEmpty(heartTime)) {
                                                    long hearTimeMillis = TimeUtils.string2Millis(heartTime);
                                                    long nowMills = TimeUtils.getNowMills();
                                                    if (nowMills - hearTimeMillis > 12 * 60 * 60 * 1000) {
                                                        //如果当前时间与心跳时间的差值大于12小时，说明设备离线
                                                        isOnline = false;
                                                    } else {
                                                        isOnline = true;
                                                    }
                                                }
                                            }

                                            dataBean.setOnline(isOnline);

                                        }
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            ecDequiAdapter.replaceData(dataBeans);
                                        } else {
                                            ecDequiAdapter.addData(dataBeans);
                                        }

                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });
    }

    /**
     * 显示保护区列表
     */
    public void showProtectPop() {
        new XPopup.Builder(ActivityUtil.getTopActivity())
                .hasShadowBg(true)
                .maxHeight(ScreenUtils.getScreenHeight() / 2)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asCenterList("请选择设备类型", deviceTypeArray,
                        null, deviceType,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                deviceType = position;
                                getDequiList(1);
                            }
                        }).show();

    }

}